package com.maoslv.controller;

import cn.hutool.core.map.MapUtil;
import com.maoslv.aop.LogAnnotation;
import com.maoslv.dto.Result;
import com.maoslv.pojo.Pagination;
import com.maoslv.pojo.Role;
import com.maoslv.pojo.User;
import com.maoslv.service.user.UserService;
import com.maoslv.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Scope("request")
public class UserController {
    @Autowired
    UserService userService;

    @Autowired
    RedisUtil redisUtil;

    @PostMapping("/list")
    @PreAuthorize("hasAnyAuthority('sys:user:list')")
    @LogAnnotation(operator = "获取用户列表")
    public Result getUserList(@RequestBody Pagination pagination) {
        Map<String, Object> userMap = new HashMap<>();
        userMap.put("name",pagination.getName());
        userMap.put("currentPage",(pagination.getCurrentPage() - 1) * 5);
        userMap.put("pageSize",pagination.getPageSize());
        List<User> userList = userService.getUserList(userMap);
        return Result.succ("获取成功", userList);
    }

    @GetMapping("/info/{id}")
    @PreAuthorize("hasAnyAuthority('sys:user:list')")
    @LogAnnotation(operator = "获取用户信息")
    public Result getUserInfo(@PathVariable Integer id) {
        User userInfo = userService.getUserInfo(id);
        if (userInfo != null) {
            return Result.succ("获取成功",userInfo);
        }
        return Result.fail("获取失败");
    }

    @PostMapping("/updateUser")
    @PreAuthorize("hasAnyAuthority('sys:user:update')")
    @LogAnnotation(operator = "更新用户")
    public Result updateUser(@RequestBody User user) {
        Map<String, Object> userMap = new HashMap<>();
        userMap.put("id",user.getId());
        userMap.put("username",user.getUsername());
        userMap.put("email",user.getEmail());
        userMap.put("state",user.getState());
        if (userService.updateUser(userMap) > 0) {
            return Result.succ("编辑成功",null);
        }
        return Result.fail("编辑失败");
    }

//    @GetMapping("/delUser/{id}")
//    @PreAuthorize("hasAnyAuthority('sys:user:del')")
//    public Result delUser(@PathVariable Integer id) {
//        List<Role> userRole = userService.getUserRole(id);
//        for (Role role : userRole) {
//            if (role.getId() == 1) {
//                return Result.fail("请先删除管理员身份");
//            }
//        }
//        if (userService.delUser(id) > 0) {
//            return Result.succ("注销成功",null);
//        }
//        return Result.fail("注销失败");
//    }

    @GetMapping("/getUserRole/{id}")
    @PreAuthorize("hasAnyAuthority('sys:user:list')")
    @LogAnnotation(operator = "获取用户角色ID")
    public Result getUserRole(@PathVariable Integer id) {
        List<Integer> roleId = userService.getRoleId(id);
        return Result.succ("获取成功", MapUtil.builder()
                                                .put("id",id)
                                                .put("roleId",roleId)
                                                .map());
    }

    @GetMapping("/getTreeData")
    @LogAnnotation(operator = "获取树形用户角色ID")
    public Result getTreeData() {
        List<Role> allRoleId = userService.getAllRole();
        return Result.succ("获取成功",allRoleId);
    }

    @PostMapping("/assignRole/{id}")
    @PreAuthorize("hasAnyAuthority('sys:user:list')")
    @LogAnnotation(operator = "分配角色")
    public Result addRole(@PathVariable Integer id, @RequestBody List<Integer> roleId, Principal principal) {
        boolean flag = false;
        if (userService.assignRole(id,roleId) > 0) {
            User byUsername = userService.getByUsername(principal.getName());
            if (id == byUsername.getId()) {
                flag = true;
            }
            return Result.succ("分配成功", flag);
        } else {
            return Result.fail("分配失败");
        }
    }

    @GetMapping("/logout")
    @LogAnnotation(operator = "退出登录")
    public Result logout(Principal principal) {
        redisUtil.del(principal.getName() + "-jwt");
        redisUtil.del(principal.getName() + "-menuList");
        User user = userService.getByUsername(principal.getName());
        redisUtil.del(user.getId() + "-jurisdiction");
        return Result.succ("退出成功", null);
    }
}
